<template>
  <div class="post-wrapper">
    <div class="post-container scrollable-wrapper" :key="refreshKey">
      <h2>发布图文</h2>
      <div class="row-title">图片列表</div>
      <div class="image-upload-row">
        <div
          v-for="(img, index) in images"
          :key="index"
          class="uploaded-image"
        >
          <img :src="img.imageUrl" @click="previewImage(img.imageUrl)" />
          <span class="delete-icon" @click.stop="removeImage(index)">×</span>
        </div>
        <div
          v-if="images.length < maxImages"
          class="image-placeholder"
          @click="triggerFileInput"
        >
          <img :src="plusIcon" class="plus-icon" />
        </div>
        <input type="file" ref="fileInput" style="display: none" @change="handleImageUpload" />
      </div>

      <div class="row-title">正文内容</div>
      <input
        type="text"
        v-model="title"
        placeholder="请输入帖子标题"
        class="title-input"
      />

      <div class="row-title">帖子内容</div>
      <textarea
        v-model="content"
        placeholder="请输入帖子内容"
        class="content-input"
      ></textarea>

      <div class="row-title">热门标签</div>
      <div class="hot-tags">
        <span
          v-for="tag in hotTags"
          :key="tag.id"
          class="hot-tag"
          :class="{ selected: isTagSelected(tag) }"
          @click="selectTag(tag)"
        >
          {{ tag.name }}
        </span>
      </div>

      <div class="row-title">搜索/创建标签</div>
      <div class="tag-search-row">
        <input
          type="text"
          v-model="tagSearch"
          placeholder="搜索或创建标签"
          @input="searchTagList"
          class="tag-search-input"
        />
        <button class="submit-button" @click="confirmTag">选中标签</button>
      </div>
      <div class="search-suggestions" v-if="searchResults.length">
        <div
          v-for="tag in searchResults"
          :key="tag.id"
          @click="selectTag(tag)"
          class="tag-suggestion"
        >
          {{ tag.name }}
        </div>
      </div>

      <div class="row-title">当前选中标签</div>
      <div class="selected-tags">
        <span v-for="(tag, index) in selectedTags" :key="tag.id" class="selected-tag">
          {{ tag.name }}
          <span class="remove-tag" @click="removeTag(index)">×</span>
        </span>
      </div>

      <div class="row-title">操作</div>
      <div class="tag-search-row">
        <button @click="submitPost" class="submit-button">发布帖子</button>
        <button @click="cancelPost" class="cancel-button">取消发布</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import plusIcon from '@/assets/community/jiahao.png'
import {
  uploadPostImg,
  deletePostImg,
  addPost,
  searchHotTags,
  searchTags,
  createTag
} from '@/api/CommunityApi'
import { ElMessage } from 'element-plus'

const images = ref([])
const maxImages = 8
const fileInput = ref(null)
const title = ref('')
const content = ref('')
const tagSearch = ref('')
const searchResults = ref([])
const hotTags = ref([])
const selectedTags = ref([])
const refreshKey = ref(0)

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleImageUpload = async (event) => {
  const file = event.target.files[0]

  if (!file) return
  try {
    const res = await (await uploadPostImg(file)).data.data
    images.value.push({ imageId: res.imageId, imageUrl: res.imgUrl })
  } catch (err) {
    console.error('图片上传失败', err)
  }
}

const removeImage = async (index) => {
  const image = images.value[index]
  await deletePostImg(image.imageId)
  images.value.splice(index, 1)
}

const previewImage = (url) => {
  window.open(url, '_blank')
}

const searchTagList = async () => {
  if (!tagSearch.value || tagSearch.value.trim() === '') {
    return
  }
  const res = await searchTags(tagSearch.value)
  searchResults.value = res.data.data
}

const confirmTag = async () => {
  const match = searchResults.value.find(t => t.name === tagSearch.value)
  if (match) {
    selectTag(match)
  } else {
    const res = await createTag(tagSearch.value)
    const newtag = {
      id : res.data.data.tagId,
      name : tagSearch.value
    }
    selectTag(newtag)
  }
  tagSearch.value = ''
  searchResults.value = []
}

const cancelPost = async () => {
  for (const img of images.value) {
    await deletePostImg(img.imageId)
  }
  images.value = []
  title.value = ''
  content.value = ''
  tagSearch.value = ''
  searchResults.value = []
  selectedTags.value = []
  refreshKey.value++
}

const selectTag = (tag) => {
  if (!selectedTags.value.find(t => t.id === tag.id)) {
    selectedTags.value.push(tag)
  }
  tagSearch.value = ''
  searchResults.value = []
}

const isTagSelected = (tag) => {
  return selectedTags.value.some(t => t.id === tag.id)
}

const removeTag = (index) => {
  selectedTags.value.splice(index, 1)
}

const submitPost = async () => {
  if (!title.value.trim()) return alert('标题不能为空')
  const imgIds = images.value.map(img => img.imageId)
  if (imgIds.length === 0) return alert('请至少上传一张图片')
  const tagsIds = selectedTags.value.map(tag => tag.id)
  try {
    await addPost(
      title.value,
      content.value,
      tagsIds,
      imgIds
    )
    ElMessage.success("发布成功")
  } catch (err) {
    console.error('发布失败', err)
  }
}

onMounted(async () => {
  const res = await searchHotTags()
  hotTags.value = res.data.data
})
</script>

<style scoped>
.post-wrapper {
  display: flex;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
}

.post-container {
  font-family: sans-serif;
  max-height: 90vh;
  overflow-y: auto;
  scrollbar-width: none;          /* Firefox */
  -ms-overflow-style: none;       /* IE & Edge */
}

.row-title {
  margin-bottom: 10px;
  margin-top: 20px;
}

.image-upload-row {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.uploaded-image {
  position: relative;
  border: 1px solid #7f6748;
}

.uploaded-image img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
}

.delete-icon {
  position: absolute;
  top: 2px;
  right: 6px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
}

.image-placeholder {
  width: 100px;
  height: 100px;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  cursor: pointer;
}

.plus-icon {
  width: 30px;
  height: 30px;
}

.title-input,
.tag-search-input {
  width: 500px;
  height: 40px;
  font-size: 16px;
  padding: 8px;
  box-sizing: border-box;
  background-color: #f0f0f0;
}

.content-input {
  width: 840px;
  height: 250px;
  font-size: 16px;
  margin-bottom: 20px;
  padding: 8px;
  box-sizing: border-box;
  resize: none;
  background-color: #f0f0f0;
}

.hot-tags {
  margin-bottom: 20px;
}

.hot-tag {
  display: inline-block;
  background: #f5f5f5;
  padding: 6px 10px;
  border-radius: 6px;
  margin-right: 10px;
  cursor: pointer;
}

.hot-tag.selected {
  background: #e0f7fa;
  border: 1px solid #26c6da;
}

.tag-search-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.search-suggestions {
  margin-bottom: 20px;
  background: #fafafa;
  border: 1px solid #ccc;
  max-width: 500px;
}

.tag-suggestion {
  padding: 8px;
  cursor: pointer;
}

.tag-suggestion:hover {
  background: #eee;
}

.selected-tags {
  margin-bottom: 20px;
}

.selected-tag {
  display: inline-block;
  background: #cde;
  padding: 6px 10px;
  border-radius: 6px;
  margin-right: 10px;
  position: relative;
}

.remove-tag {
  margin-left: 6px;
  cursor: pointer;
  color: red;
}

.submit-button {
  background-color: #a9b8a1;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  border-radius: 6px;
}

.cancel-button {
  background-color: #ae9b7e;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  border-radius: 6px;
}
</style>
